import React from 'react';
import './index.scss';

let lyricTimer = null;
let animationTimer = null;

class Lyric extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lyric: '',
      tlyric: '',
      lyrics: [],
      currentId: 0,
      highLightTimeStamp: 0,
    }
  }

  getLyric(id) {
    if (!id) { return; }
    this.setState({ currentId: id });

    window.axios.get('/lyric', {
      params: {
        id,
      }
    })
    .then((response) => {
      let lyric = response.data.lrc.lyric;
      let tlyric = response.data.tlyric.lyric;
      let lyrics = [];
      lyrics = lyric.split('\n').map(l => {
        let time = '00:00:00';
        let timeStamp = 0;
        let lp = '';
        if (l.indexOf('[')>-1) {
          time = l.split('[')[1].split(']')[0];
          lp = l.split('[')[1].split(']')[1];
          let m = parseInt(time.split('.')[0].split(':')[0]);
          let s = parseInt(time.split('.')[0].split(':')[1]);
          let ms = parseInt(parseInt(time.split('.')[1]));
          timeStamp = (60000 * m) + (1000 * s) + ms;
        }
        return { time, lp, timeStamp }
      });
      if (!lyrics[lyrics.length-1].timeStamp) {
        lyrics.pop();
      }
      
      this.setState({
        lyric,
        tlyric,
        lyrics,
      })

      this.resetTimer();
    })
    .catch((error) => {
      console.log(error);
    });
  }

  resetTimer() {
    if (lyricTimer) {
      clearInterval(lyricTimer);
    }
    lyricTimer = setInterval(() => {
      this.setHighLight();
    }, 100)
  }

  setHighLight() {
    let s = parseInt(window._Music.currentTime.toString().split('.')[0]);
    let ms = parseInt(window._Music.currentTime.toFixed(3).split('.')[1]);
    let currentTimeStamp = (s * 1000) + ms;
    let highLightTimeStamp = 0;
    let highLightLyricIndex = 0;
    this.state.lyrics.some((l, index) => {
      if ( currentTimeStamp >= l.timeStamp ) {
        highLightTimeStamp = this.state.lyrics[index].timeStamp
        highLightLyricIndex = index;
        return false;
      }
      return true;
    })

    if (this.state.highLightTimeStamp !== highLightTimeStamp) {
      this.setState({ highLightTimeStamp });
      this.animationScroll(highLightLyricIndex);
    }
  }

  animationScroll(highLightLyricIndex) {
    let lyric = document.querySelector('.lyric');
    let highLightElement = document.querySelector('.lyric').querySelectorAll('p')[highLightLyricIndex];
    let oldScrollTop = lyric.scrollTop;
    let newScrollTop = highLightElement.offsetTop - lyric.offsetTop - (lyric.offsetHeight / 3);
    let averageScrollTop = (newScrollTop - oldScrollTop) / 10;
    // 滚动时间为 0.2s
    if (animationTimer) { return; }
    let count = 0;
    animationTimer = setInterval(() => {
      if (count < 10) {
        count++;
        lyric.scrollTop = lyric.scrollTop + averageScrollTop;
      } else {
        clearInterval(animationTimer);
        animationTimer = null;
        count = 0;
      }
    }, 16)
  }

  componentWillReceiveProps(nextProps) {
    this.getLyric(nextProps.id)
  }

  render () {

    let lyricsDom = this.state.lyrics.map(({time, lp, timeStamp}) => {
      return <p key={time} className={timeStamp===this.state.highLightTimeStamp ? 'high-light' : ''}>{lp}</p>
    });

    return (
      <div className="lyric">{lyricsDom}</div>
    )
  }
}

export default Lyric;
